package com.tff.gmall.interceptors;

import com.alibaba.fastjson.JSON;
import com.tff.gmall.annotations.LoginRequired;
import com.tff.gmall.util.CookieUtil;
import com.tff.gmall.util.HttpclientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Fafa Tuo
 * @version 1.0
 * @date 2021/7/9 16:38
 * 登录拦截器
 */
@Component
public class AuthInterceptors extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断被拦截的请求的访问的方法的注解是否是需要拦截的
        HandlerMethod hm = (HandlerMethod) handler;
        LoginRequired methodAnnotation = hm.getMethodAnnotation(LoginRequired.class);
        StringBuffer requestURL1 = request.getRequestURL();
        System.out.println(requestURL1);
        //这里判断的是否需要拦截
        if(methodAnnotation == null){
            //直接让过
            return true;
        }
        //已经拦截，是否需要必须登录才能访问
        boolean logSuccess = methodAnnotation.logSuccess();

        String token = "";
        String oldToken = CookieUtil.getCookieValue(request, "oldToken", true);
        String newToken = request.getParameter("token");

        if(StringUtils.isNotBlank(oldToken)){
            token = oldToken;
        }
        if(StringUtils.isNotBlank(newToken)){
            token = newToken;
        }
        //进入拦截器的拦截方法
        //把验证提出来，调用验证中心验证
        String success = "fail";
        Map<String,String> successMap = null;
        if(StringUtils.isNotBlank(token)){

            String ip = request.getHeader("x-forwarded-for");   //从nginx转发中获取客户端的ip
            if (StringUtils.isBlank(ip)){
                ip = request.getRemoteAddr();   //从request请求中获取ip
                if(StringUtils.isBlank(ip)){
                    //理论上来讲应该做异常处理
                    ip = "127.0.0.1";
                }
            }

            String strSuccessJson = HttpclientUtil.doGet("http://localhost:7071/verify?token=" + token+"&currentIp="+ip);
            successMap = JSON.parseObject(strSuccessJson,Map.class);
            success = successMap.get("status");
        }
        if (logSuccess){
            //必须登录之后才能做的事情
            /*if(StringUtils.isBlank(token)){
                //token为空，说明新老token都不存在，从来没有登录过。直接踢回
            }else {
                //token不为空，不管是新的还是老的token，直接校验
            }*/
            if(!success.equals("success")){
                //验证未通过,重定向到passport
                StringBuffer requestURL = request.getRequestURL();
                response.sendRedirect("http://localhost:7071/index?ReturnUrl="+requestURL);
            return false;
            }else {
                //验证通过，覆盖cookie中的token
                //验证通过，需要将token携带的用户信息写入
                request.setAttribute("memberId",successMap.get("memberId"));
                request.setAttribute("nickname",successMap.get("nickname"));

                if (StringUtils.isNotBlank(token)){
                    //覆盖cookie
                    CookieUtil.setCookie(request,response,"oldToken",token,60*69*2,true);
                }
            }
        }else{
            //不是登录也可以访问，例如，购物车等
           /* if (StringUtils.isBlank(token)){
            }else {
                //验证
            }*/
            if(success.equals("success")){
                //验证通过，需要将token携带的用户信息写入
                request.setAttribute("memberId",successMap.get("memberId"));
                request.setAttribute("nickname",successMap.get("nickname"));

                if (StringUtils.isNotBlank(token)){
                    //覆盖cookie
                    CookieUtil.setCookie(request,response,"oldToken",token,60*69*2,true);
                }
            }
        }

        return true;
    }
}
